//
//  ScrollLayout.swift
//  CTCollectionViewDemo
//
//  Created by GodCoder on 2019/8/7.
//  Copyright © 2019 CTCollectionView. All rights reserved.
//

import UIKit

class ScrollLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let customLayouts = super.layoutAttributesForElements(in: rect)
        
        if self.scrollDirection == .horizontal {
            let centerX = CGFloat((self.collectionView?.contentOffset.x)!) + CGFloat((self.collectionView?.bounds.size.width)!*0.5)
            for layout in customLayouts! {
                /// item中心点与界面中心的距离
                let center = abs(layout.center.x - centerX)
                let scale = 1/(1+center/((self.collectionView?.bounds.size.width)! - self.minimumLineSpacing))
                
                layout.transform = CGAffineTransform(scaleX: scale, y: scale)
            }
        } else {
            let centerY = CGFloat((self.collectionView?.contentOffset.y)!) + CGFloat((self.collectionView?.bounds.size.height)!*0.5)
            for layout in customLayouts! {
                /// item中心点与界面中心的距离
                let center = abs(layout.center.y - centerY)
                let scale = 1/(1+center/((self.collectionView?.bounds.size.height)! - self.minimumLineSpacing))
                
                layout.transform = CGAffineTransform(scaleX: scale, y: scale)
            }
        }

        return customLayouts
    }
    
    /// 重新设置中心点位置
    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        var point = super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
        if self.scrollDirection == .horizontal {
            let page = round(proposedContentOffset.x/(self.itemSize.width + self.minimumLineSpacing))
            let pageX = self.itemSize.width * (page + 0.5) - (self.collectionView?.bounds.size.width)! * 0.5 + self.minimumLineSpacing*page
            point.x = pageX
        }
        else {
            let page = round(proposedContentOffset.y/(self.itemSize.height + self.minimumLineSpacing))
            let pageY = self.itemSize.height * (page + 0.5) - (self.collectionView?.bounds.size.height)! * 0.5 + self.minimumLineSpacing*page
            point.y = pageY
        }
        
        return point
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
}
